package com.concurrency.example.aqs.test.p1;

import com.concurrency.example.aqs.test.Computable;

import java.util.Map;
import java.util.concurrent.*;

public class Memoizer3<A, V> implements Computable<A, V> {
    private final Map<A, Future<V>> cache = new ConcurrentHashMap<>();
    private final Computable<A, V> c;

    public Memoizer3(Computable<A, V> c) {
        this.c = c;
    }

    public Map<A, Future<V>> getCache() {
        return cache;
    }

    @Override
    public V compute(A a) throws InterruptedException {
        while (true) {
            Future<V> f = cache.get(a);
            if (f == null) {
                //FutureTask博客  http://www.importnew.com/25286.html
                FutureTask<V> task = new FutureTask<>(() -> c.compute(a));
                f = cache.putIfAbsent(a, task);
                if(f == null){
                    f = task;
                    task.run();
                }
            }
            try {
                return f.get();
            } catch (CancellationException e) {
                //如果计算被取消，那么应该从缓存中移除
                cache.remove(a, f);
            } catch (ExecutionException e) {
               //TODO
            }
        }
    }
}

